package com.heima.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.heima.article.entity.ApAuthor;
import com.heima.article.feign.ArticleFeign;
import com.heima.common.dto.PageResponseResult;
import com.heima.common.dto.ResponseResult;
import com.heima.common.enums.AppHttpCodeEnum;
import com.heima.common.enums.UserEnum;
import com.heima.media.entity.WmUser;
import com.heima.media.feign.MediaFeign;
import com.heima.user.dto.AuthDto;
import com.heima.user.entity.ApUser;
import com.heima.user.entity.ApUserRealname;
import com.heima.user.mapper.ApUserRealnameMapper;
import com.heima.user.service.IApUserRealnameService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.user.service.IApUserService;
import io.seata.spring.annotation.GlobalTransactional;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * <p>
 * APP实名认证信息表 服务实现类
 * </p>
 *
 * @author itheima
 * @since 2022-05-15
 */
@Service
public class ApUserRealnameServiceImpl extends ServiceImpl<ApUserRealnameMapper, ApUserRealname> implements IApUserRealnameService {

    @Autowired
    private MediaFeign mediaFeign;

    @Autowired
    private ArticleFeign articleFeign;

    @Autowired
    private IApUserService apUserService;


    /**
     * 根据实名认证状态查询列表
     *
     * @param dto 入参 状态条件
     * @return
     */
    @Override
    public ResponseResult listByStatus(AuthDto dto) {
        //1.构建查询条件对象
        LambdaQueryWrapper<ApUserRealname> queryWrapper = new LambdaQueryWrapper<>();
        if (dto.getStatus() != null) {
            queryWrapper.eq(ApUserRealname::getStatus, dto.getStatus());
        }
        //2.构建分页对象
        IPage<ApUserRealname> page = new Page<>(dto.getPage(), dto.getSize());

        //3.执行分页查询
        page = this.page(page, queryWrapper);

        //4.封装响应数据
        return new PageResponseResult(dto.getPage(), dto.getSize(), page.getTotal(), page.getRecords());
    }


    /**
     * 审核通过/失败业务（作业）
     *
     * @param dto  app用户ID，审核失败原因
     * @param type 0：审核失败  1：审核通过
     * @return
     */
    @Override
    @GlobalTransactional(rollbackFor = Exception.class)
    public ResponseResult auth(AuthDto dto, int type) {
        //1.根据APP用户ID查询实名认证记录  修改状态
        //1.1 查询得到实名认证记录
        ApUserRealname apUserRealname = this.getById(dto.getId());
        //1.2 根据操作类型-审核失败 则更新失败原因 返回
        if (type == UserEnum.USER_REALNAME_OP_FAIL.getVal()) {
            //1.2.1 TODO 审核驳回逻辑
            return ResponseResult.okResult();

        }
        //1.2.2 审核通过逻辑
        apUserRealname.setStatus(UserEnum.USER_REALNAME_STATUS_PASS.getVal());
        this.updateById(apUserRealname);

        //2.远程调用自媒体微服务新增自媒体用户
        //2.1 根据APP用户ID查询APP用户信息 用来封装自媒体用户对象
        //ApUser apUser = apUserService.getById(dto.getId());
        ApUser apUser = apUserService.getById(apUserRealname.getUserId());
        //2.2 封装自媒体用户对象-远程调用新增自媒体用户
        if (apUser != null) {
            WmUser wmUser = createWmUser(apUser);
            //3.远程调用文章微服务新增文章作者用户
            //3.1 构建作者对象 完成新增作者
            ApAuthor apAuthor = createAuthor(apUser, wmUser);
            if (apAuthor != null) {
                //3.2 远程调用自媒体微服务更新自媒体用户作者ID
                wmUser.setApAuthorId(apAuthor.getId());
                mediaFeign.updateWmUser(wmUser);
                //3.3 更新APP用户表中 用户标记 用户审核状态
                apUser.setFlag(UserEnum.APPUSER_TYPE_WEMEDIA.getVal());
                apUser.setIsCertification(true);
                apUser.setIsIdentityAuthentication(true);
                apUserService.updateById(apUser);
            }
        }
        return ResponseResult.okResult();
    }


    /**
     * 构建作者用户对象 完成远程调用
     *
     * @param apUser APP用户基本信息
     * @param wmUser 自媒体用户
     * @return
     */
    private ApAuthor createAuthor(ApUser apUser, WmUser wmUser) {
        //1.封装作者用户对象
        ApAuthor apAuthor = new ApAuthor();
        apAuthor.setName(apUser.getName());
        apAuthor.setType(UserEnum.AUTHOR_TYPE_WEMEDIA.getVal());
        apAuthor.setUserId(apUser.getId());
        apAuthor.setWmUserId(wmUser.getId());
        //2.远程调用文章微服务完成新增
        ResponseResult<ApAuthor> result = articleFeign.saveApAuthor(apAuthor);
        if (result != null && result.getCode().equals(AppHttpCodeEnum.SUCCESS.getCode())) {
            return result.getData();
        }
        return null;
    }


    /**
     * 构建自媒体用户对象 完成远程调用
     *
     * @param apUser APP用户基本信息
     * @return
     */
    private WmUser createWmUser(ApUser apUser) {
        //1.封装自媒体用户对象  从基础用户信息对象copy
        WmUser wmUser = new WmUser();
        BeanUtils.copyProperties(apUser, wmUser);
        wmUser.setApUserId(apUser.getId());
        wmUser.setNickname(apUser.getName());
        wmUser.setStatus(UserEnum.USER_REALNAME_STATUS_PASS.getVal());
        wmUser.setType(UserEnum.APPUSER_TYPE_NORMAL.getVal());
        //todo 作者ID 还缺
        //2.远程调用自媒体微服务完成新增
        ResponseResult<WmUser> result = mediaFeign.saveWmUser(wmUser);
        if (result != null && result.getCode().equals(AppHttpCodeEnum.SUCCESS.getCode())) {
            return result.getData();
        }
        return null;
    }
}
